package archive

import (
	"archive/zip"
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"github.com/cheggaaa/pb/v3"
	"io"
	"os"
	"path/filepath"
)

// DecompressZipPackageFile 解压zip文件
func DecompressZipPackageFile(ctx context.Context, file *os.File, size int64, target string, callback func(total int64, current int64)) error {
	var bar = pb.Full.Start64(size)
	var proxy = NewProxyReaderAt(file, bar, make(chan int64, 100))
	defer func() {
		bar.Finish()
		_ = proxy.Close()
	}()

	var reader, err = zip.NewReader(proxy, size)
	if nil != err {
		return err
	}

	goroutine.Go(func() {
		var current int64
		for n := range proxy.ch {
			current += n
			callback(size, current)
		}
	})

	for _, hdr := range reader.File {
		if nil != ctx.Err() {
			return ctx.Err()
		}

		if err := os.MkdirAll(filepath.Join(target, filepath.Dir(hdr.Name)), 0755); nil != err {
			return err
		}

		if hdr.FileInfo().IsDir() {
			continue
		}

		ft, err := os.OpenFile(filepath.Join(target, hdr.Name), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, hdr.FileInfo().Mode())
		if nil != err {
			return err
		}

		fs, err := hdr.Open()
		if nil != err {
			return err
		}

		if _, err := io.Copy(ft, fs); nil != err {
			return err
		}

		_ = ft.Close()
		_ = fs.Close()
	}

	return nil
}
